﻿using System;
namespace WinAPI
{
    class HandleGuard : System.Runtime.InteropServices.SafeHandle
    {
        public class HandleInvalidException : Exception { }
        //true means that object is resource owner
        public HandleGuard(IntPtr _handle)
            : base(_handle, true)
        {
            if (IsInvalid)
                throw new HandleInvalidException();
        }
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        public extern static bool CloseHandle(IntPtr handle);

        public override bool IsInvalid
        {//Zero-1 means 0xffffffff
            get { return IsClosed || handle == IntPtr.Zero - 1; }
        }
        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }
}
